<div class="layui-fluid" id="user-chart-index" lay-title="用户管理">
	<div class="layui-col-xs12">
		<div class="layui-card">
			<div class="layui-tab layui-tab-brief userBlock" lay-filter="index-order">
				<!-- <ul class="layui-tab-title">
					<li class="layui-this">用户管理</li>
				</ul> -->
				<div class="nepadmin-pad-t10 nepadmin-pad-b10 nepadmin-pad-l10 nepadmin-pad-r10 searchBlock">
					<div class="layui-btn actionBtn AddUserBtn">添加用户</div>
					<form class="searchForm layui-form" lay-filter="searchUserForm">
						<input class="layui-input searchItem" name="name" placeholder="运营人" />
						<button class="layui-btn actionBtn" lay-submit lay-filter="searchUserForm">查询</button>
					</form>
				</div>
				<div class="layui-tab-content" style="padding:0;">
					<div class="layui-tab-item layui-show nepadmin-table-full">
						<table lay-filter="user-table"></table>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>


<script type="text/html" id="userIndexAction">
	<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script>
layui.use(['admin','form', 'element', 'table'],function(admin, form, element, table) {
	var $ = layui.jquery
	var view = $('#user-chart-index')
	var editObj = '';
	var tableObj = '';
	element.render('progress')
	form.render(null, 'addUserForm');
	
	// var userLoginInfo = JSON.parse(window.localStorage.getItem('putPlat')).user;
	// if(userLoginInfo.role == 1){
	// 	$('.userBlock').html('<p class="noRole"><img src="./nepadmin/images/noRole.svg"/>暂无权限</p>')
	// }else{
		tableObj = table.render({
			size: 'nob',
			elem: '[lay-filter="user-table"]',
			url: apiUrl + '/index.php/user/index/index?token=' + JSON.parse(window.sessionStorage.getItem('agricultural')).token,
			limit: 15,
			method: 'POST',
			page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
				layout: ['prev', 'page', 'next', 'count', 'skip', 'limit'] //自定义分页布局
				,first: false //不显示首页
				,last: false //不显示尾页
				,limits: [15, 20, 30, 40, 50, 60]
			},
			cols: [[
				{title: '用户名', field: 'username', align: 'center'},
				{title: '运营人', field: 'name', align: 'center'},
				{title: '操作',  toolbar: '#userIndexAction', align: 'center'},
			]],
			done: function(res){
				console.log(res)
				if(res.code == 2){
					tokenExpired()
				}
			}
		})
	// }

	
	
	// 查询
	form.on('submit(searchUserForm)', function (data) {
		tableObj.reload({
			where:data.field,
			page: {
				curr: 1 //重新从第 1 页开始
			}
		})
	    return false;
	});
	
	table.on('tool(user-table)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
	  var data = obj.data; //获得当前行数据
	  var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
	  var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
	  console.log(data)
	 
	  if(layEvent === 'del'){ //删除
		layer.confirm('确定要删除这一条数据吗', function(index){
		  
		  //向服务端发送删除指令
		  $.ajax({
		    url: apiUrl + '/index.php/user/index/delete?token=' + JSON.parse(window.sessionStorage.getItem('agricultural')).token,
		    data:{
				id: data.id,
				role: JSON.parse(window.localStorage.getItem('agricultural')).user.role_id
			},
		  	type: 'POST',
		      success:function(res){
		  		console.log(res)
		  		if(res.code == 0){
					layer.close(index);
		  			layer.closeAll();
		  			layer.msg('删除成功')
					obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
		  		}else if(res.code == 2){
					tokenExpired()
				}else{
		  			layer.msg(res.msg)
		  		}
		          
		      },
		      complete:function(){
		          //loading.hide();
		      }
		  });
		});
	  } else if(layEvent === 'edit'){ //编辑
		$('#addUserFixed input[name=role]').val(JSON.parse(window.localStorage.getItem('agricultural')).user.role_id)
		$('#addUserFixed input[name=id]').val(data.id);
		$('#addUserFixed input[name=username]').val(data.username);
		$('#addUserFixed input[name=password]').val(data.password);
		$('#addUserFixed input[name=name]').val(data.name);
		form.render();
		var width = isMobile() ? '90%' : '400px'
		layer.open({
			type: 1,
			title: '修改用户信息',
			area: width,
			content: $('#addUserFixed') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
		});
		editObj = obj;
	  }
	});
	
	// 添加弹框
	$('.AddUserBtn').click(function(){
		$('#addUserFixed')[0].reset();
		$('#addUserFixed input[name=role]').val(JSON.parse(window.localStorage.getItem('agricultural')).user.role_id)
		var width = isMobile() ? '90%' : '400px'
		layer.open({
			type: 1,
			title: '添加用户信息',
			area: width,
			content: $('#addUserFixed') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
		});
	})
	
	// 提交
	form.on('submit(addUserForm)', function (data) {
	    console.log(data.field);
		if(data.field.id){
			// 修改
				$.ajax({
			    url: apiUrl + '/index.php/user/index/edit?token=' + JSON.parse(window.sessionStorage.getItem('agricultural')).token,
			    data:data.field,
				type: 'POST',
			    success:function(res){
					console.log(res)
					if(res.code == 0){
						layer.closeAll();
						$('#editUserFixed').hide();
						editObj.update(data.field);
					}else if(res.code == 2){
						tokenExpired()
					}else{
						layer.msg(res.msg)
					}
			        
			    },
			    complete:function(){
			        //loading.hide();
			    }
			});
		}else{
			// 添加
			$.ajax({
			    url: apiUrl + '/index.php/user/index/add?token=' + JSON.parse(window.sessionStorage.getItem('agricultural')).token,
			    data:data.field,
				type: 'POST',
			    success:function(res){
					console.log(res)
					if(res.code == 0){
						layer.closeAll();
						layer.msg('添加成功')
						tableObj.reload();
					}else if(res.code == 2){
						tokenExpired()
					}else{
						layer.msg(res.msg)
					}
			        
			    },
			    complete:function(){
			        //loading.hide();
			    }
			});
		}
		
		
	    return false;
	});
	

})
</script>


<style type="text/css">
	#addUserFixed{
		margin: 10px;
		overflow: hidden;
	}

	#addUserFixed .layui-form-label,
	#editUserFixed .layui-form-label {
		width: 65px;
	}

	#editUserFixed .editCol .layui-form-label {
		width: 133px;
	}

	#addUserFixed .layui-input-block,
	#editUserFixed .layui-input-block {
		margin-left: 99px;
	}
	
</style>
